$(() => {
  // get dom elem
  let $width          = $('#width'),
      $height         = $('#height'),
      $btnCal         = $('#calc'),
      $form           = $('#main'),
      $perimeter      = $('#perimeter'),
      $widthValidate  = $('#width-validate'),
      $heightValidate = $('#height-validate'),
      $area           = $('#area');
  $forkMeGH.show("https://github.com/wangding/rectangle")

  // 字符级别校验
  $width.keypress((e) => {
    filterKey(e)
  });

  $height.keypress((e) => {
    filterKey(e)
  });
  
  // 字段级别校验
  $width.focusout(() => {
    if(!validate($width, $widthValidate)){
      $width.select();
    }
  })

  $height.focusout(() => {
    if(!validate($height, $heightValidate)){
      $height.select();
    }
  })

  // calc button click
  $btnCal.click(()=> {

    // get value
    let w = Number($width.val()),
        h = Number($height.val());

    // validate 表单级别验证
    if(validate($width, $widthValidate) && validate($height,$heightValidate)){

      // calc
      let p = (w + h) * 2;
      let a = w * h;

      // 解决浮点舍入误差的问题
      function roundFractional(x, n) {
        return Math.round(x * Math.pow(10, n)) / Math.pow(10, n);
      }
        
      // output
      $perimeter.val(roundFractional(p,2));
      $area.val(roundFractional(a,2)); 
    }
  })
})

function filterKey(e) {
  var key = e.key,
      pos = e.target.selectionStart,
      val = e.target.value;
      

  // 过滤非法字符
  if(/[abcdf-zABCDF-Z`~!@#$%^&*()\=_+[\]{}|;:'",<>/?\\]/.test(e.key)) {
    e.preventDefault();
    return;
  }

  // 校验小数点
  if(key === '.'){
    if(pos === 0 || val.indexOf('.') !== -1) {
      e.preventDefault();
      return;
    }

    if(pos === 1 && val.substring(0,1) === '-') {
      e.preventDefault();
      return;
    }
  } 

  // 校验e和E
  if(key === 'E' || key === 'e') {
    if(pos ===0 || val.indexOf('e') !== -1 || val.indexOf('E') !== -1){
      e.preventDefault();
      return;
    }

    if(pos === 1 && val.substring(0,1) === '-') {
      e.preventDefault();
      return;
    }
  }
  
  // 校验负号
  if(key === '-') {
    if(pos === 0) {
      e.preventDefault();
      return;
    }
    if(pos > 0){
      if(/[0-9.]/.test(val.slice(pos-1, pos)) || val.indexOf('-') !== -1){
        e.preventDefault();
        return;
      }
    }
  }
}

// 表单级别校验函数
function validate(input, output) {
  // is empty
  if(input.val() === '') {
    output.html('该字段不能为空');
    return false;
  } else {
    output.html('');
  }

  // is number
  let val = Number(input.val());

  if(isNaN(val)) {
    output.html('该字段应该是数值');
    return false;
  } else {
    output.html('')
  }
  
  // is +
  if(val < 0) {
    output.html('该数值不能小于零');
    return false;
  } else {
    output.html('');
  }

  return true
}
